package juc2.synchronizeddome;

/**
 * 偏向锁机制示例
 */
public class BiasedLockDemo {
    // 共享资源（锁对象）
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        // JDK 17中偏向锁默认关闭，若需测试需添加JVM参数：
        // -XX:+UseBiasedLocking -XX:BiasedLockingStartupDelay=0
        // 1. 延迟启动，确保偏向锁机制生效（JVM默认延迟4秒开启偏向锁）
        Thread.sleep(5000);

        // 2. 单线程重复获取锁
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            synchronized (lock) {
                // 临界区：空操作，仅模拟重复加锁
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
        long end = System.currentTimeMillis();

        System.out.println("单线程循环加锁耗时：" + (end - start) + "ms");
    }
}
